package com.dai.zhenfujin.my;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.MainActivity;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.bean.UserBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.my.activity.release.CompanyAddressActivity;
import com.dai.zhenfujin.my.activity.release.NameActivity;
import com.dai.zhenfujin.utils.PhotoUtil;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.dai.zhenfujin.my.activity.ReleaseActivity.CODE_CAMERA_REQUEST;
import static com.dai.zhenfujin.my.activity.ReleaseActivity.CODE_GALLERY_REQUEST;
import static com.dai.zhenfujin.my.activity.ReleaseActivity.CODE_RESULT_REQUEST;

public class MyInfoActivity extends BaseActivity implements View.OnClickListener {

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");

    private TextView tvName, tvSex, tvDuty, tvWorkingRange,
            tvCompanyName, tvCompanyAddress, tvCompanyDetailedAddress;

    private FrameLayout fl_img;
    private RelativeLayout release_sex,release_name;
    private Button bt_save;
    private ImageView my_head_portrait;
    private TextView release_text_name;
    private Dialog dialog, dialogHead;
    private Uri imageUri;
    private Uri cropImageUri;
    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int OUTPUT_X = 480;
    private static int OUTPUT_Y = 480;
    private OSS oss;
    private boolean isShowImg,isShowImg2;
    private UserBean userBean;
    private int type2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_info_activity);
        userBean = (UserBean) getIntent().getSerializableExtra("userBean");
        setPermissions();
        initView();
        initListener();
    }

    private void setPermissions() {
        RxPermissions rxPermissions = new RxPermissions(MyInfoActivity.this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.READ_PHONE_STATE
                        , Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                .subscribe(granted -> {
                    if (granted) {
                        //  Toast.makeText(MainActivity.this, "同意权限", Toast.LENGTH_SHORT).show();
                    } else {
                        //  Toast.makeText(MainActivity.this, "拒绝权限", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    private void initView() {
        type2 = getIntent().getIntExtra("type",0);
        fl_img = findViewById(R.id.fl_img);
        tvName = findViewById(R.id.title_textview);
        release_sex = findViewById(R.id.release_sex); //修改密码
        my_head_portrait = findViewById(R.id.my_head_portrait);
        bt_save = findViewById(R.id.bt_save); //
        release_name = findViewById(R.id.release_name); //
        release_text_name = findViewById(R.id.release_text_name); //名字
        tvName.setText("修改我的资料");
        bt_save.setOnClickListener(this);
        release_sex.setOnClickListener(v -> {
            startActivity(new Intent(MyInfoActivity.this, ResetPasswordActivity.class));
        });

        fl_img.setOnClickListener(v -> finish());
        release_name.setOnClickListener(v -> {
            Intent name = new Intent(MyInfoActivity.this, NameActivity.class);
            startActivityForResult(name, 1);
        });
        my_head_portrait.setOnClickListener(v -> {
            showHeadDialog();
        });

        if(null != userBean){
            isShowImg2 = true;
            Glide.with(this).load(userBean.getUser_logo()).into(my_head_portrait);
            release_text_name.setText(userBean.getUser_name());
        }
    }

    private void showHeadDialog() {
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait, null);
        view.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        dialogHead.show();//显示对话框//设置Dialog从窗体底部弹出
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    private void initListener() {

    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_shoot://拍摄
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.dai.zhenfujin.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                dialogHead.dismiss();

                break;
            case R.id.dialog_photo_album://相册
                PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
                dialogHead.dismiss();
                break;
            case R.id.release_company_detailed_address://详细地址
                Intent intent2 = new Intent(this, CompanyAddressActivity.class);
                intent2.putExtra("type", 7);
                startActivityForResult(intent2, 7);
                break;

            case R.id.dialog_cancel://取消
                dialogHead.dismiss();
                break;
            case R.id.bt_save://保存
                if (null == userBean) {
                    if (!isShowImg) {
                        UIUtils.showToastSafe("请更换头像");
                        return;
                    }
                }

                if (TextUtils.isEmpty(release_text_name.getText().toString().trim())){
                    UIUtils.showToastSafe("请输入名字");
                    return;
                }

                if (isShowImg) {  //已上传
                    initOss(); //配置OSS
                    ossToken(revitionImageSize(cropImageUri.getPath()));
                }else if (isShowImg2){
                    saveUserInfo(userBean.getUser_logo());
                }
                break;
        }
    }

    private void ossToken(String path) {
        // 构造上传请求
        final String imgName = UIUtils.getCurTimeMills() + "";
        PutObjectRequest put = new PutObjectRequest("zenfujin-bucket",  "profile/" + imgName + ".jpg", path);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                String url_log = "https://image.zhenfujin.net/" + "profile/" + imgName + ".jpg";
                runOnUiThread(() -> saveUserInfo(url_log));
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("onFailure", serviceException.getErrorCode());
                    Log.e("onFailure", serviceException.getRequestId());
                    Log.e("onFailure", serviceException.getHostId());
                    Log.e("onFailure", serviceException.getRawMessage());
                    UIUtils.showToastSafe("图片上传失败，请重新上传");
                }
            }
        });
    }

    private void saveUserInfo(String url_log) {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("user_logo",url_log);
        params2.put("user_name",release_text_name.getText().toString().trim());
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.EDITLOGO, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean resultBean) {
                if (type2 == 1){
                    startActivity(new Intent(MyInfoActivity.this, MainActivity.class).putExtra("showRed",1));
                    SPUtils.put(MyInfoActivity.this,"welcome",true);
                    UIUtils.showToastSafe("完善资料成功");
                    finish();
                }else {
                    UIUtils.showToastSafe("修改资料成功");
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.UPDATA_USER_PRODUCT);
                    EventBus.getDefault().post(messageEvent);
                    finish();
                }
            }
        });
    }

    private String revitionImageSize(String path) {
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; //只读取图片，不加载到内存中
            BitmapFactory.decodeStream(in, null, options);
            in.close();

            options.inJustDecodeBounds = false;
            int w = options.outWidth;
            int h = options.outHeight;
            float hh = 800f;//
            float ww = 480f;//
            int be = 1;
            if (w > h && w > ww) {
                be = (int) (options.outWidth / ww);
            } else if (w < h && h > hh) {
                be = (int) (options.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            options.inSampleSize = be;//设置采样率

            options.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
            options.inPurgeable = true;// 同时设置才会有效
            options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
            String newPath = Constants.APP_FOLD + path.substring(path.lastIndexOf("/"));
            saveBitmapToFile(bitmap, newPath);
            // bitmap = BitmapFactory.decodeFile(path, options);
            return newPath;
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param _file
     * @throws IOException
     */
    public void saveBitmapToFile(Bitmap bitmap, String _file)
            throws IOException {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initOss() {
        String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
        // 在移动端建议使用STS方式初始化OSSClient。
        // 更多信息可查看sample 中 sts 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
        //   OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.ACCESS_ID, Constants.ACCESS_KEY);

        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
        if (requestCode == 1 && resultCode == 11) {
            String name = intent.getStringExtra("name");
            release_text_name.setText(name);
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtil.getPath(this, intent.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.dai.zhenfujin.FileProvider", new File(newUri.getPath()));
                    }
                    PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        showImages(bitmap);
                    }
                    break;
                default:
            }
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void showImages(Bitmap bitmap) {
        isShowImg = true;
        my_head_portrait.setImageBitmap(bitmap);
    }
}
